package com.heima.comment.service.impl;
import java.math.BigDecimal;
import java.util.*;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;

    @Autowired
    CommentHotService commentHotService;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        // 检查参数
        if (dto == null || dto.getArticleId() == null || dto.getContent() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 检查是否登陆，未登录不能评论
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser user = userFeign.findUserById(Long.valueOf(apUser.getId()));
        // 检查内容不能大于140个字
        if (dto.getContent().length() >= 140){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"文字内容长度过长");
        }
        // 阿里云审核
        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if (suggestion != "pass"){
                throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"输入的文字包含违规信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 插入评论信息
        ApComment apComment = new ApComment();
        apComment.setAuthorId(user.getId());
        apComment.setAuthorName(user.getName());
        apComment.setEntryId(dto.getArticleId());
        apComment.setType((short)0);
        apComment.setImage(user.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short)0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setContent(dto.getContent());

        mongoTemplate.insert(apComment);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        // 检查参数
        if (dto == null || dto.getCommentId() == null || dto.getOperation() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据评论id查询评论信息
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"该评论信息不见了");
        }
        // 查询点赞信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"需要先登陆");
        }
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
        ApCommentLike apCommentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        // 如果方式为0代表点赞
        Integer likes = 0;
        if (dto.getOperation() == 0){
            likes = apComment.getLikes();
            likes = likes + 1;
            apComment.setLikes(likes);
            mongoTemplate.save(apComment);
            // 添加评论点赞信息
            if (apCommentLike != null){
                throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"你已经点过赞,不能重复点赞");
            }
            apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation((short)0);
            mongoTemplate.save(apCommentLike);
        }else {
            // 取消点赞
            likes = apComment.getLikes();
            likes = likes - 1;
            apComment.setLikes(likes);
            mongoTemplate.save(apComment);
            // 删除点赞记录
            mongoTemplate.remove(apCommentLike);
        }
        // 点赞成功，计算当前评论是不是热点评论 判断当前点赞数量是否大于五，且还是普通评论
        if (likes >= 5 && apComment.getFlag() == 0) {
            // 计算当前评论是不是热点评论
            commentHotService.hotCommentExecutor(Long.valueOf(dto.getCommentId()),apComment);
            log.info("点赞成功 ==> ");
        }
        Map map = new HashMap<>();
        map.put("likes",likes);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        // 检查参数
        if (dto == null || dto.getArticleId() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Date minDate = dto.getMinDate();
        if (minDate == null){
            minDate = new Date();
        }
        dto.checkParam();

        // 查看当前登陆用户
        ApUser user = AppThreadLocalUtils.getUser();
        // 检查评论id
        // 根据文章id查出所有的评论信息

        List<ApComment> apComments = null;
        // 是首页
        if (dto.getIndex() == 1){
            // 先查询热评
            Query hotQuery = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                    .and("flag").is(1))
                    .with(Sort.by(Sort.Direction.DESC,"likes"));
            apComments = mongoTemplate.find(hotQuery, ApComment.class);
            int hotSize = apComments.size();
            if (apComments != null && hotSize > 0){
                // 再查询除热评以外的普通评论，组合起来
                int size = dto.getSize()-hotSize;
                Query normalQuery = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                        .and("createdTime").lt(minDate)
                        .and("flag").is(0))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                        .limit(size);
                List<ApComment> normalApComments = mongoTemplate.find(normalQuery, ApComment.class);
                apComments.addAll(normalApComments);
            }else {
                Query entryIdQuery = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                        .and("createdTime").lt(minDate)
                        .and("flag").is(0))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                        .limit(dto.getSize());
                apComments = mongoTemplate.find(entryIdQuery, ApComment.class);
            }

        }else {
            Query entryIdQuery = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                    .and("createdTime").lt(minDate)
                    .and("flag").is(0))
                    .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                    .limit(dto.getSize());
            apComments = mongoTemplate.find(entryIdQuery, ApComment.class);
        }



        // 未登录直接返回评论列表
        if (user == null){
            return ResponseResult.okResult(apComments);
        }
        // 如果用户登陆了，判断自己是否点过赞
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                .and("authorId").is(user.getId()));
//        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);

        ArrayList<ApCommentVo> apCommentVos = new ArrayList<>();
        Query likeApComment = null;
        for (ApComment apComment : apComments) {
            // 获取每个id并封装成一个id集合
            String id = apComment.getId();
            likeApComment = Query.query(Criteria.where("commentId").is(id).and("operation").is(0));
            ApCommentLike commentLike = mongoTemplate.findOne(likeApComment, ApCommentLike.class);
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment, apCommentVo);
            if (commentLike != null){
                apCommentVo.setOperation((short) 0);
            }
            apCommentVos.add(apCommentVo);
        }
        return ResponseResult.okResult(apCommentVos);
    }
}
